package com.lin.zoo.view;

import com.lin.zoo.controller.AnimalController;
import com.lin.zoo.util.DataBase;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.Vector;

public class AnimalFeederPage {

    private JFrame frame;
    private JButton delButton,addButton,setNameButton,setTypeButton,setIntroButton,setAgeButton,setHealButton,setParkIdButton;
    private JTable jTable;
    private DefaultTableModel mol;
    private JScrollPane scrollPane;
    private JPanel panel;
    private JTextField jText=new JTextField("请在此输入修改的数据");

    private Vector<String> rowVector;
    private Vector<Vector<String>> dataVector;
    private Connection con;
    private PreparedStatement state;
    private ResultSet rs;

    private AnimalController animalController;

    public AnimalController getAnimalController() {
        return animalController;
    }

    public void setAnimalController(AnimalController animalController) {
        this.animalController = animalController;
    }

    public JButton getDelButton() {
        return delButton;
    }

    public void setDelButton(JButton delButton) {
        this.delButton = delButton;
    }

    public JButton getAddButton() {
        return addButton;
    }

    public void setAddButton(JButton addButton) {
        this.addButton = addButton;
    }

    public JButton getSetNameButton() {
        return setNameButton;
    }

    public void setSetNameButton(JButton setNameButton) {
        this.setNameButton = setNameButton;
    }

    public JButton getSetTypeButton() {
        return setTypeButton;
    }

    public void setSetTypeButton(JButton setTypeButton) {
        this.setTypeButton = setTypeButton;
    }

    public JButton getSetIntroButton() {
        return setIntroButton;
    }

    public void setSetIntroButton(JButton setIntroButton) {
        this.setIntroButton = setIntroButton;
    }

    public JButton getSetAgeButton() {
        return setAgeButton;
    }

    public void setSetAgeButton(JButton setAgeButton) {
        this.setAgeButton = setAgeButton;
    }

    public JButton getSetHealButton() {
        return setHealButton;
    }

    public void setSetHealButton(JButton setHealButton) {
        this.setHealButton = setHealButton;
    }

    public JButton getSetParkIdButton() {
        return setParkIdButton;
    }

    public void setSetParkIdButton(JButton setParkIdButton) {
        this.setParkIdButton = setParkIdButton;
    }

    public JTextField getjText() {
        return jText;
    }

    public void setjText(JTextField jText) {
        this.jText = jText;
    }

    public void createAndShowGUI() throws SQLException{
        setAnimalController(new AnimalController());
        frame=new JFrame("动物信息管理系统");//新窗口
        frame.setVisible(true);//窗口设置为可视
        frame.setSize(1000,400);//窗口大小1000*400
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        // 显示窗口，关闭仅为子窗口
        frame.setResizable(false);
        //固定窗口大小不被修改
        frame.setLocationRelativeTo(null);
        //窗口处于中央
        rowVector= new Vector<>();
        rowVector.add("id");
        rowVector.add("动物名字");
        rowVector.add("动物种类");
        rowVector.add("动物介绍");
        rowVector.add("动物年龄");
        rowVector.add("动物健康状态");
        rowVector.add("所属园区");//设置列的名称
        mol =new DefaultTableModel();
        try {
            con =DataBase.getCon();
            state = con.prepareStatement("select * from animal");
            rs=state.executeQuery();
        } catch (ClassNotFoundException e) {
            System.out.println("数据读取错误"+this.getClass().getName());
        }//直接在view中调用了数据库，希望这个问题可以在日后想办法改变
        setData(rs);
        DataBase.close(state, con);
        jTable=new JTable(mol);
        jTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        scrollPane=new JScrollPane(jTable);

        TableColumn introductionColumn = jTable.getColumnModel().getColumn(3);
        introductionColumn.setPreferredWidth(550);//修改介绍一列的行距

        TableColumn idColumn = jTable.getColumnModel().getColumn(0);
        idColumn.setPreferredWidth(20);//修改id一行的行距

        TableColumn parkIdColumn = jTable.getColumnModel().getColumn(6);
        parkIdColumn.setPreferredWidth(60);//修改park_id一行的行距

        jTable.setRowHeight(50);
        frame.add(scrollPane,BorderLayout.CENTER);//添加滚轮
        init();
        frame.add(panel,BorderLayout.SOUTH);
        //删除按钮
        getDelButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int seletedRow=jTable.getSelectedRow();
                seletedRow=jTable.convertRowIndexToModel(seletedRow);//选中行
                Object id=jTable.getValueAt(seletedRow+0,0);//读取选中行的id
                if(seletedRow !=-1){
                    mol.removeRow(seletedRow);
                }
                getAnimalController().delAnimal(id);
                JOptionPane.showMessageDialog(null, "删除成功", null, JOptionPane.PLAIN_MESSAGE);
            }
        });
        //添加动物
        getAddButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Vector<String> row= new Vector<>();
                try{
                    con=DataBase.getCon();
                    state=con.prepareStatement("INSERT INTO animal (name,type,introduction,age,healthstate,park_id) VALUES (?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS);
                    state.setObject(1," ");
                    state.setObject(2," ");
                    state.setObject(3," ");
                    state.setObject(4," ");
                    state.setObject(5," ");
                    state.setObject(6,0);
                    state.executeUpdate();//完成新的动物信息的插入，空信息表的创建
                    try (ResultSet rs = state.getGeneratedKeys()) {
                        if (rs.next()) {
                            String id = rs.getString(1);
                            row.add(id);
                            row.add(" ");
                            row.add(" ");
                            row.add(" ");
                            row.add(" ");
                            row.add(" ");
                            row.add("0");//将新创建的信息反馈到界面以便进一步地修改，默认所属园区0
                            mol.addRow(row);
                        }
                    }
                }catch (SQLException | ClassNotFoundException ex) {
                    ex.printStackTrace();
                }
                JOptionPane.showMessageDialog(null, "添加成功", null, JOptionPane.PLAIN_MESSAGE);

            }
        });
        //修改动物名字
        getSetNameButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int seletedRow=jTable.getSelectedRow();
                seletedRow=jTable.convertRowIndexToModel(seletedRow);//记录选中行
                Object id=jTable.getValueAt(seletedRow+0,0);
                String name=jText.getText();
                jTable.setValueAt(name,seletedRow,1);//反馈到界面
                jTable.repaint();
                jText.setText("请在此输入需要修改的数据");
                getAnimalController().setName(id,name);
                JOptionPane.showMessageDialog(null, "修改成功", null, JOptionPane.PLAIN_MESSAGE);
            }
        });
        //修改动物种类
        getSetTypeButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int seletedRow=jTable.getSelectedRow();
                seletedRow=jTable.convertRowIndexToModel(seletedRow);//记录选中行
                Object id=jTable.getValueAt(seletedRow+0,0);
                String type=jText.getText();
                jTable.setValueAt(type,seletedRow,2);//反馈到界面
                jTable.repaint();//表格数据刷新
                jText.setText("请在此输入需要修改的数据");
                getAnimalController().setType(id,type);
                JOptionPane.showMessageDialog(null, "修改成功", null, JOptionPane.PLAIN_MESSAGE);
            }
        });
        //修改动物介绍
        getSetIntroButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int seletedRow=jTable.getSelectedRow();
                seletedRow=jTable.convertRowIndexToModel(seletedRow);//记录选中行
                Object id=jTable.getValueAt(seletedRow+0,0);
                String introduce=jText.getText();
                jTable.setValueAt(introduce,seletedRow,3);//反馈到界面
                jTable.repaint();
                jText.setText("请在此输入需要修改的数据");
                getAnimalController().setIntroduce(id,introduce);
                JOptionPane.showMessageDialog(null, "修改成功", null, JOptionPane.PLAIN_MESSAGE);
            }
        });
        //修改动物年龄
        getSetAgeButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int seletedRow=jTable.getSelectedRow();
                seletedRow=jTable.convertRowIndexToModel(seletedRow);//记录选中行
                Object id=jTable.getValueAt(seletedRow+0,0);
                String age=jText.getText();
                jTable.setValueAt(age,seletedRow,4);//反馈到界面
                jTable.repaint();
                jText.setText("请在此输入需要修改的数据");
                getAnimalController().setAge(id,age);
                JOptionPane.showMessageDialog(null, "修改成功", null, JOptionPane.PLAIN_MESSAGE);
            }
        });
        //修改动物健康状况
        getSetHealButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int seletedRow=jTable.getSelectedRow();
                seletedRow=jTable.convertRowIndexToModel(seletedRow);//记录选中行
                Object id=jTable.getValueAt(seletedRow+0,0);//读取选中行的id
                String health=jText.getText();//用户数据的读取
                jTable.setValueAt(health,seletedRow,5);//反馈到界面
                jTable.repaint();//表格数据刷新
                jText.setText("请在此输入需要修改的数据");
                getAnimalController().setHealth(id,health);
                JOptionPane.showMessageDialog(null, "修改成功", null, JOptionPane.PLAIN_MESSAGE);
            }
        });
        //修改动物所在园区
        getSetParkIdButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int seletedRow=jTable.getSelectedRow();
                seletedRow=jTable.convertRowIndexToModel(seletedRow);//记录选中行
                Object id=jTable.getValueAt(seletedRow+0,0);//读取选中行的id
                String parkId=jText.getText();//用户数据的数据
                jTable.setValueAt(parkId,seletedRow,6);//反馈到界面
                jTable.repaint();
                jText.setText("请在此输入需要修改的数据");
                getAnimalController().setPark(id,parkId);
                JOptionPane.showMessageDialog(null, "修改成功", null, JOptionPane.PLAIN_MESSAGE);
            }
        });


    }

    public void init(){
        panel=new JPanel();
        delButton=new JButton("删除");
        setTypeButton=new JButton("修改动物种类");
        setNameButton=new JButton("修改动物名字");
        setAgeButton=new JButton("修改动物年龄");
        setIntroButton=new JButton("修改动物介绍");
        setHealButton=new JButton("修改动物健康状况");
        setParkIdButton=new JButton("修改动物所在园区");
        addButton =new JButton("添加");//设置新的按钮文本

        panel.setLayout(new GridLayout(2,1));

        panel.add(addButton);
        panel.add(delButton);
        panel.add(setNameButton);
        panel.add(setTypeButton);
        panel.add(setIntroButton);
        panel.add(setAgeButton);
        panel.add(setHealButton);
        panel.add(setParkIdButton);
        panel.add(jText);//添加按钮到承载的panel
    }
//将读取的ResultSet数据放置到dataVector
    public void setData(ResultSet rs) throws SQLException {
        dataVector = new Vector<>();
        while(rs.next()) {
            Vector<String> vector = new Vector<>();
            for (int i = 1; i <= 7; i++)//7 代表列数
                vector.add(rs.getString(i));//添加数据库数据到vector
            dataVector.add(vector);//添加vector数据到dataVector
        }
        mol.setDataVector(dataVector,rowVector);//最后将数据输入至mol
    }
}
